package cn.ava.basic.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Desc :  spring工具类
 * 普通类调用Spring bean对象
 * 说明：此类需要放到主函数同包或者子包下才能被扫描，否则失效。
 * User : RICK
 * Time : 2017/8/22 10:32
 */
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }

    /**
     * Desc :  获取applicationContext
     * User : RICK
     * Time : 2017/8/22 10:36
     */

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * Desc :  通过beanName获取bean
     * User : RICK
     * Time : 2017/8/22 10:37
     */
    public static Object getBean(String beanName) {
        return getApplicationContext().getBean(beanName);
    }

    /**
     * Desc :  通过class获取bean
     * User : RICK
     * Time : 2017/8/22 10:38
      */
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }


    /**
     * Desc : 通过name、class返回指定的bean
     * User : RICK
     * Time : 2017/8/22 10:48
      */
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name,clazz);
    }

}